import db from '@dfeidao/atom-nodejs/db';
import log from '@dfeidao/atom-nodejs/logger/log';
import { IncomingHttpHeaders } from 'http';
import { systemid } from '../atom/config';
interface Message {
	productid: string;
	grade_no: string;
	class_id: string;
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string;
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}
interface D {
	grade: string;
	class_name: string;
	week: string;
	section: string;
	subject_name: string;
}
export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {
	log('Service begin path:app-my-schedule/s003,action_id:' + action_id);

	log('Service end path:app-my-schedule/s003,action_id:' + action_id);
	const query = db.complex_query(action_id, session_id, systemid);
	const data1 = await query
		.add_field('teacher_schedule', 'week', 'week')
		.add_field('teacher_schedule', 'section', 'section')
		.add_field('teacher_schedule', 'grade', 'grade')
		.add_field('teacher_schedule', 'subject_name', 'subject_name')
		.add_field('teacher_schedule', 'class_name', 'class_name')
		.where_eq('teacher_schedule', 'grade_no', message.grade_no)
		.where_eq('teacher_schedule', 'productid', message.productid)
		.where_eq('teacher_schedule', 'class_id', message.class_id)
		// .groupby('teacher_schedule', 'section')
		// .page(2, 1)
		.orderby('section')
		.exec<D>();
	const arr = data1.reduce((p, c) => {
		if (Array.from(p.keys()).indexOf(c.section) === -1) {

			const d = { 星期一: {}, 星期二: {}, 星期三: {}, 星期四: {}, 星期五: {}, 星期六: {}, 星期日: {} };
			d[c.week] = { ...c, grade_class_name: c.subject_name };
			p.set(c.section, { section: c.section, data: d });
		} else {
			p.get(c.section).data[c.week] = { ...c, grade_class_name: c.subject_name };

			// p.get(c.section).data.push(c);
		}
		return p;
	}, new Map());
	const dest = Array.from(arr.values());
	return {
		data: { dest }
	};
}
